import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { getDeptListApi } from "@/apis/dept"

export const useUserStore = defineStore(
  'user',
  () => {
    /** token */
    const token = ref('')

    /** 当前选中的id */
    const selectedDeptInfo = ref({})

    /** 用户信息 */
    const userInfo = ref({})

    /** 获取token */
    const getToken = computed(() => token.value)

    /** 获取用户信息 */
    const getUserInfo = computed(() => userInfo.value)

    /** 获取部门信息 */
    const getDeptList = computed(() => userInfo.value.departmentList)

    /** 获取当前选中的deptId */
    const getSelectedDept = computed(() => selectedDeptInfo.value)

    /** 设置菜单信息 */
    function setUser(data: any) {
      token.value = data.token || ''
      userInfo.value = data.user_info || {}
      data.user_info && setDepartment(data.user_info.departmentIds || [])
    }

    /** 设置部门信息 */
    async function setDepartment(departmentIds: string[]) {
      if (!departmentIds.length) return;
      const data = await getDeptListApi({})
      const departmentList = data.list.filter((item: any) => departmentIds.includes(item._id))
      userInfo.value.departmentList = departmentList;
      setSelectedDeptInfo(departmentList[0])
    }

    /** 设置选中的deptId */
    function setSelectedDeptInfo(item: any) {
      selectedDeptInfo.value = item
    }

    /** 清空缓存内容 */
    function clearUser() {
      setUser({})
    }

    /** 退出登录 */
    function logOut() {
      clearUser()
      // 刷新页面，清除所有信息
      location.reload()
    }

    return {
      setUser,
      clearUser,
      logOut,
      token,
      userInfo,
      getToken,
      getUserInfo,
      getDeptList,
      selectedDeptInfo,
      getSelectedDept,
      setSelectedDeptInfo
    }
  },
  {
    persist: {
      key: 'USER',
      paths: ['token', 'userInfo', 'selectedDeptInfo'],
      storage: sessionStorage
    }
  }
)
